﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.IO;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    

    [WebMethod]
    public string GetToken()
    {

        // http://www.c-sharpcorner.com/UploadFile/scottlysle/UploadwithCSharpWS05032007121259PM/UploadwithCSharpWS.aspx

        string token = DateTime.Now.ToString("yyyyMMddHHmm") + "_" + Guid.NewGuid().ToString();

        // Create Folder 
        DirectoryInfo di = GetTargetFolder(token);
        di.Create();

        // Log IP Address
        try
        {
            File.WriteAllText(Path.Combine(di.FullName, "Request.txt"), HttpContext.Current.Request.UserHostAddress);
        }
        catch (Exception ex)
        {
            // TODO: Log
        }
        
        return token;

    }

    [WebMethod]
    public string Cancel(string token)
    {
        DirectoryInfo di = GetTargetFolder(token);
        string fileName = Path.Combine(di.FullName, "cancel.txt");
        File.WriteAllText(fileName, "Canceled " + DateTime.Now.ToString());
        return "Done";
    }

    [WebMethod]
    public string SubmitFileChunk(string token, byte[] contents, string name, int part)
    {

        DirectoryInfo di = GetTargetFolder(token);
        string fileName = Path.Combine(di.FullName, name + "." + part.ToString("0000"));

        MemoryStream memoryStream = new MemoryStream(contents);

        FileStream fileStream = new FileStream(fileName, FileMode.Create);
        memoryStream.WriteTo(fileStream);
        memoryStream.Close();
        fileStream.Close();
        fileStream = null;
        memoryStream = null;

        return "File Has " + contents.Length.ToString() + " bytes";

    }

    [WebMethod]
    public string AssembleFile(string token, string name)
    {

        DirectoryInfo di = GetTargetFolder(token);
        FileInfo[] fileChunks = di.GetFiles(name + ".*");
        Dictionary<int, FileInfo> fileChunksDict = new Dictionary<int, FileInfo>();
        foreach (FileInfo file in fileChunks)
        {
            int part = int.Parse(file.Extension.TrimStart('.'));
            fileChunksDict.Add(part, file);
        }

        List<byte> fileBytes = new List<byte>();

        for (int i = 1; i <= fileChunks.Length; i++)
        {
            FileInfo fileChunk = fileChunksDict[i];
            byte[] chunkBytes = File.ReadAllBytes(fileChunk.FullName);
            fileBytes.AddRange(chunkBytes);
        }

        File.WriteAllBytes(Path.Combine(di.FullName,  name), fileBytes.ToArray());

        return "File Assembled!";

    }

    [WebMethod]
    public string CleanUpChunks(string token, string name)
    {
        DirectoryInfo di = GetTargetFolder(token);
        FileInfo[] fileChunks = di.GetFiles(name + ".*");
        Dictionary<int, FileInfo> fileChunksDict = new Dictionary<int, FileInfo>();
        foreach (FileInfo file in fileChunks)
        {
            if (file.Name.ToUpper() != name.ToUpper())
            {
                file.Delete();    
            }
        }
        return "Chunks Cleaned Up";
    }

    [WebMethod]
    public string Where(string x)
    {
        if (x == "Hebrews 11:1")
        {
            return HttpContext.Current.Request.PhysicalApplicationPath;
        }
        else
        {
            return "Invalid x";
        }
    }

    private static DirectoryInfo GetTargetFolder(string tokenName)
    {
        string logsFolder = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "Logs");
        string tokenFolder = Path.Combine(logsFolder, tokenName);
        DirectoryInfo di = new DirectoryInfo(tokenFolder);
        return di;
    }
    
}
